package com.lswms.modules.lswms.service.impl.base;

import java.util.Arrays;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.modules.lswms.MEGConstant;
import com.lswms.modules.lswms.dao.base.CodeDao;
import com.lswms.modules.lswms.dto.base.CodeDTO;
import com.lswms.modules.lswms.entity.base.CodeEntity;
import com.lswms.modules.lswms.service.base.CodeService;
import com.lswms.modules.lswms.service.base.CodelistService;

import lombok.extern.slf4j.Slf4j;

/**
 * 盘点
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-08-30
 */
@Service
@Slf4j
public class CodeServiceImpl extends CrudServiceImpl<CodeDao, CodeEntity, CodeDTO> implements CodeService {

	@Autowired
	private CodelistService codelistService;
	
	@Autowired
	private CodeDao codeDao;

    @Override
    public QueryWrapper<CodeEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String codename = (String)params.get("codename");
        String code = (String)params.get("code");
       
        QueryWrapper<CodeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.like(StringUtils.isNotBlank(code), "code", code);
        wrapper.like(StringUtils.isNotBlank(codename), "name", codename);
        
        wrapper.orderByDesc("addtime");
        return wrapper;
    }

	@Override
	public void deleteByCode(String[] codes) {
		//删除主信息
		 QueryWrapper<CodeEntity> wrapper = new QueryWrapper<>();
		 wrapper.in(StringUtils.isNoneBlank(codes), "code",   Arrays.asList(codes)) ;
		 codeDao.delete(wrapper);
		
		 //删除从信息
		codelistService.deleteByCode(codes);
		
	}

	@Override
	public String validate(CodeDTO dto) {
		String code =dto.getCode() ; 
		
		if( StringUtils.isEmpty(code)) {
			return  String.format(MEGConstant.IS_NOT_EMPTY, "Code")  ;
		}
		if( StringUtils.isEmpty(dto.getCodename())) {
			return  String.format(MEGConstant.IS_NOT_EMPTY, "CodeName")  ;
		}
		
		 QueryWrapper<CodeEntity> wrapper = new QueryWrapper<>();
		 wrapper.eq("code", code);
		 Integer count = codeDao.selectCount(wrapper);
		 if(count>0) {
			 return  String.format(MEGConstant.VALUE_EXISTS, code )  ;
		 }
		return "";
	}


}